import React from 'react'
import ReactDOM from 'react-dom'
import { Spin, Popover, Button, message } from "antd"
import { autorun } from "mobx"
import { WeaTag, WeaCheckbox, WeaInput, WeaDialog, WeaAlertPage, WeaLocaleProvider, WeaInputLocale } from 'ecCom'
import TaskTag from '../../components/task/TaskTag'
import * as taskMainApis from '../../apis/task/taskMain'

const getLabel = WeaLocaleProvider.getLabel
const formatMultiLang = WeaLocaleProvider.formatMultiLang
const getUserLanguage = WeaLocaleProvider.getUserLanguage
const getCurrentLabel = WeaInputLocale.getCurrentLabel

export default class TagChoiceBox extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            showTagAddIcon: true,
            tagAddValue: "",
            datas: [],
            visible: false,
            spinning: false,
            tagSettingDialogVisible: false,
            ...props,
        }
    }

    componentWillMount() {
        const { visible } = this.state
        visible && this.getListDatas()
    }

    componentWillReceiveProps(newProps) {
        const oldVisible = this.state.visible
        this.setState({
            ...this.state,
            ...newProps
        }, () => {
            const { visible } = this.state
            !oldVisible && visible && this.getListDatas()
        })
    }

    componentDidMount() {
        const { isDialog = true } = this.state
        if (!isDialog) {
            document.addEventListener("click", (e) => {
                let needHideBox = true
                let currentNode = e.target
                while (currentNode && currentNode.tagName != "BODY") {
                    if (currentNode.className && currentNode.className.indexOf("wea-workrelate-tag-choice-box-popover-reset") > -1) {
                        needHideBox = false
                        break
                    }
                    currentNode = currentNode.parentNode
                }

                if (needHideBox) {
                    this.setState({
                        visible: false
                    })
                }
            })

            let interval = window.setInterval(() => {
                let ds = document.getElementsByClassName("ant-popover-placement-bottom")
                if (ds && ds.length > 0) {
                    window.clearInterval(interval)
                    for (let i = 0; i < ds.length; i++) {
                        ds[i].onclick = (e) => {
                            e.stopImmediatePropagation()
                            let node = e.target
                            let parentNode = e.target.parentNode
                            if (node && node.classList) {
                                let classvalue = node.classList.value
                                if (!classvalue && parentNode) {
                                    classvalue = parentNode.classList.value || ""
                                }
                                if (classvalue.indexOf("ant-btn") > -1) {
                                    ds[i].classList.add("ant-popover-hidden")
                                }
                            }
                        }
                    }
                }
            }, 100)
        }
    }

    componentWillUnmont() { }

    getListDatas = () => {
        this.setState({
            spinning: true
        })

        taskMainApis.taskTag({
            operate: "searchList",
            includeAdmin: "1"
        }).then(res => {
            this.setState({
                spinning: false
            })

            const { checkedIds = [] } = this.state
            let datas = []
            res.datas.forEach((d, i) => {
                let data = {
                    id: d.id + "",
                    name: d.name,
                    color: d.color
                }
                data.checked = checkedIds.indexOf(d.id + "") !== -1
                datas.push(data)
            })

            this.setState({
                datas
            })
        })
    }

    onTagAddButtonClick = () => {
        let { tagAddValue, datas } = this.state
        this.setState({
            tagAddValue: ""
        }, () => {
            // let defaultColor = "#6aa84f"
            let defaultColor = "#" + Math.random().toString(16).slice(2, 8)
            if (tagAddValue && tagAddValue.trim().length > 0) {
                tagAddValue = tagAddValue.trim()

                this.setState({
                    spinning: true
                })
                taskMainApis.taskTag({
                    operate: "save",
                    tagname: tagAddValue,
                    color: defaultColor
                }).then(res => {
                    this.setState({
                        spinning: false
                    })
                    if (res.status == "1") {
                        this.setState({
                            datas: [{ id: res.id + "", name: formatMultiLang(tagAddValue), color: defaultColor, checked: true }, ...datas]
                        })
                    }
                })
            } else {
                message.warn(getLabel(506468, '标签名称不能为空!'))
            }
        })
    }

    onTagChoiceBoxBottomCancleallClick = () => {
        const { onCallBack, datas } = this.state
        this.setState({
            visible: false
        }, () => {
            onCallBack && typeof onCallBack === "function" && onCallBack("0", datas.filter((d, i) => d.checked))
        })
    }

    onBottomSureClick = () => {
        const { onCallBack, datas } = this.state
        this.setState({
            visible: false
        }, () => {
            onCallBack && typeof onCallBack === "function" && onCallBack("1", datas.filter((d, i) => d.checked))
        })
    }

    onDialogClose = () => {
        const { onDialogClose } = this.state
        this.setState({
            showTagAddIcon: true,
            visible: false
        }, () => {
            onDialogClose && typeof onDialogClose === "function" && onDialogClose()
        })
    }

    render() {
        const { isDialog = true, style = {}, datas, visible, spinning, popoverTrigger = "click",
            popoverPlacement = "bottomLeft", dialogIconClass = "icon-coms-implement", dialogIconBgcolor = "rgb(150, 53, 138)",
            showTagAddIcon, tagAddValue = "", tagSettingDialogVisible, checkedIds, onSettingSureClick } = this.state

        const boxtype = isDialog ? "dialog" : "popover"

        const commonBoxListCom = (
            <div 
                className={"wea-workrelate-tag-choice-box-" + boxtype + "-list"}
            >
                {
                    datas.map((tag, ti) => {
                        return (
                            <div className={"wea-workrelate-tag-choice-box-" + boxtype + "-list-item"}>
                                <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@qtvedy@${tag.id}`}
                                    value={tag.checked ? "1" : "0"}
                                    onChange={(value) => {
                                        tag.checked = value == 1
                                    }}
                                />
                                <span title={formatMultiLang(tag.name)}>
                                    <WeaTag ecId={`${this && this.props && this.props.ecId || ''}_WeaTag@cjojm6@${tag.id}`}
                                        key={tag.id}
                                        id={tag.id}
                                        closable={false}
                                        color={tag.color}
                                        style={{ marginLeft: 8 }}
                                    >
                                        {formatMultiLang(tag.name)}
                                    </WeaTag>
                                </span>
                            </div>
                        )
                    })
                }
                {
                    datas.length === 0 &&
                    <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@yd7asl`}
                        icon={<i className="icon-coms-New-SMS" />}
                        iconSize={40}

                    >
                        <div className={"wea-workrelate-tag-choice-box-" + boxtype + "-list-emptytxt"}>
                            {getLabel(83553, "暂无数据")}
                        </div>
                    </WeaAlertPage>
                }
            </div>
        )

        const commonBoxAddCom = (
            <div className={"wea-workrelate-tag-choice-box-" + boxtype + "-add"}>
                {
                    !isDialog &&
                    <i className="icon-coms-Enlarge" onClick={() => this.setState({ showTagAddIcon: false })} style={{ display: showTagAddIcon ? "inline-block" : "none" }} />
                }
                <span style={{ display: !isDialog && showTagAddIcon ? "none" : "inline-flex" }} className={"wea-workrelate-tag-choice-box-" + boxtype + "-add-opr"}>
                    <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@ucltu9`}
                        placeholder={isDialog ? getLabel('518160', '请输入标签名称')  : ""}
                        style={{ width: isDialog ? 200 : 151 }}
                        inputType={"multilang"}
                        // value={formatMultiLang(tagAddValue)}
                        value={tagAddValue}
                        viewAttr={isDialog ? 3 : 2}
                        onChange={value => {
                            this.setState({
                                tagAddValue: value
                            })
                        }}
                    />
                    <span 
                        className={"wea-workrelate-tag-choice-box-" + boxtype + "-add-sure"}
                        style={{marginLeft: isDialog ? "25px" : "10px"}}
                    >
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@9sp5vj`} type="primary" onClick={this.onTagAddButtonClick}>{getLabel('517866', '添加')}</Button>
                    </span>
                    {
                        !isDialog &&
                        <span className={"wea-workrelate-tag-choice-box-" + boxtype + "-add-cancle"}>
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8gb2rt`} onClick={() => {
                                this.setState({
                                    showTagAddIcon: true,
                                    tagAddValue: ""
                                })
                            }}>
                                {getLabel(201, '取消')}
                            </Button>
                        </span>
                    }
                </span>
            </div>
        )

        return (
            <div className={this.props.classStyle ? this.props.classStyle : ""}>
                {
                    !isDialog ?
                        <Popover ecId={`${this && this.props && this.props.ecId || ''}_Popover@eo2oy3`}
                            trigger={popoverTrigger}
                            overlayClassName={"wea-workrelate-tag-choice-box-" + boxtype + "-reset"}
                            placement={popoverPlacement}
                            visible={visible}
                            content={
                                <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@whwm98`} spinning={spinning}>
                                    <span className={"wea-workrelate-tag-choice-box-" + boxtype}>
                                        <div className={"wea-workrelate-tag-choice-box-" + boxtype + "-top"}>
                                            <span className={"wea-workrelate-tag-choice-box-" + boxtype + "-top-text"}>
                                                {getLabel('516381', '选择标签')}
                                            </span>
                                            <span className={"wea-workrelate-tag-choice-box-" + boxtype + "-top-icon"}>
                                                <i title={getLabel(30884, '标签设置')} className="icon-coms-Flow-setting" onClick={() => {
                                                    this.setState({
                                                        visible: false,
                                                        showTagAddIcon: true,
                                                        tagSettingDialogVisible: true
                                                    })
                                                }} />
                                            </span>
                                        </div>
                                        {
                                            commonBoxListCom
                                        }
                                        {
                                            commonBoxAddCom
                                        }
                                        <div className={"wea-workrelate-tag-choice-box-" + boxtype + "-bottom"}>
                                            <span className={"wea-workrelate-tag-choice-box-" + boxtype + "-bottom-cancleall"}>
                                                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rxfawy`} onClick={this.onTagChoiceBoxBottomCancleallClick}>{getLabel('516382', '取消所有标记')}</Button>
                                            </span>
                                            <span className={"wea-workrelate-tag-choice-box-" + boxtype + "-bottom-sure"}>
                                                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@0osp86`} type="primary" onClick={this.onBottomSureClick}>{getLabel('826', '确定')}</Button>
                                            </span>
                                        </div>
                                    </span>
                                </ Spin>
                            }
                        >
                            <i
                                className="icon-coms02-Label"
                                title={getLabel('516383', '编辑标签')}
                                onClick={
                                    (e) => {
                                        e.nativeEvent.stopImmediatePropagation()
                                        let newVisible = !visible
                                        this.setState({
                                            visible: newVisible,
                                            showTagAddIcon: true
                                        }, () => {
                                            newVisible && this.getListDatas()
                                        })
                                    }
                                }
                            />
                        </Popover>
                        :
                        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@v7ssrh`}
                            icon={dialogIconClass}
                            iconBgcolor={dialogIconBgcolor}
                            title={
                                <div style={{
                                    display: "flex",
                                    flexDirection: "row",
                                    alignItems: "center",
                                    justifyContent: "space-between"
                                }}>
                                    <span>
                                        {getLabel('516381', '选择标签')}
                                    </span>
                                    <i
                                        title={getLabel(30884, '标签设置')}
                                        className="icon-coms-Flow-setting"
                                        style={{
                                            fontSize: 18,
                                            cursor: "pointer"
                                        }}
                                        onClick={() => {
                                            this.setState({
                                                tagSettingDialogVisible: true,
                                                // visible: false
                                            })
                                        }}
                                    />
                                </div>
                            }
                            visible={visible}
                            buttons={[
                                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@bmwf0j@sure`} type="primary" onClick={this.onBottomSureClick}>{getLabel('826', '确定')}</Button>,
                                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@08usvq@canclesign`} type="primary" onClick={this.onTagChoiceBoxBottomCancleallClick}>{getLabel('516382', '取消所有标记')}</Button>,
                                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vyh711@cancle`} onClick={this.onDialogClose}>{getLabel(201, '取消')}</Button>,
                            ]}
                            onCancel={this.onDialogClose}
                            style={{
                                width: style.width || 650,
                                height: style.height || 350
                            }}
                            children={
                                <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@k0wiei`} spinning={spinning}>
                                    <div
                                        className={"wea-workrelate-tag-choice-box-" + boxtype + "-content-wrapper"}
                                        ref={ref => {
                                            if (ref) {
                                                ref.style.height = this.dialogBodyHeight + "px"
                                            }
                                        }}
                                    >
                                        {
                                            commonBoxListCom
                                        }
                                        {
                                            commonBoxAddCom
                                        }
                                    </div>
                                </Spin>
                            }
                            ref={ref => {
                                if (ref) {
                                    this.dialogBodyHeight = ref.state.height || 0
                                }
                            }}
                        />
                }

                {tagSettingDialogVisible &&
                    <TaskTag ecId={`${this && this.props && this.props.ecId || ''}_TaskTag@x3lxgo`}
                        createvisable={tagSettingDialogVisible}
                        disabledIds={checkedIds}
                        onlyClose={(type, datas) => {
                            this.setState({ tagSettingDialogVisible: false })
                            if (type == "1") {   // 确定
                                this.getListDatas()
                                typeof onSettingSureClick === "function" && onSettingSureClick(datas)
                            }
                        }}
                    />
                }
            </div>
        )
    }

}